package com.ld.common.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ld.admin.controller.AdminBasicController;
import com.ld.admin.model.affix.AffixModel;
import com.ld.admin.model.system.SysMenuModel;
import com.ld.admin.plugin.cache.MenuCacheUtil;
import com.ld.admin.service.user.UserService;
import com.ld.common.config.web.LdGlobal;
import com.ld.common.config.web.LdStaticParams;
import com.ld.common.model.SortModel;
import com.ld.common.service.SortService;
import com.ld.common.service.SystemInitService;
import com.ld.common.util.systeminit.SystemInitModel;
import com.ld.common.util.systeminit.SystemInitUtil;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.version.Version;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "通用过滤器")
@Controller
public class CommonController extends AdminBasicController<Object> {
    @Autowired
    public SortService sortService;
    @Autowired
    public UserService userService;
    @Autowired
    public SystemInitService systemInitService;

//    @ApiOperation(value = "页面跳转", notes = "用于没有业务逻辑单纯跳转的页面")
//    @RequestMapping(path = "/to/{param1}/{param2}", method = RequestMethod.GET)
//    public String leftBar(@PathVariable String param1, @PathVariable String param2) {
//        return param1 + "/" + param2;
//    }

    @ApiOperation(value = "后台页面跳转", notes = "用于没有业务逻辑单纯跳转的页面")
    @RequestMapping(path = "${shieldsb.adminPath}/to/**", method = RequestMethod.GET)
    public String adminSkip2Page() {
        setAttributes();
        String uri = request.getServletPath();
        uri = uri.replace(adminPath + "/to/", "/");
        log.warn(uri);
        return uri;
    }

    @ApiOperation(value = "后台左侧菜单", notes = "左侧菜单获取")
    @RequestMapping(path = "${shieldsb.adminPath}/leftBar", method = RequestMethod.GET)
    public String adminLeftBar() {
        setAttributes();
        Long pid = getLong("pid");
        request.setAttribute("parMenu", MenuCacheUtil.getTopMenusByid(pid));
        List<SysMenuModel> menus = MenuCacheUtil.getLeftBarMenus(pid);
        request.setAttribute("menus", menus);
        return "a/leftBar";
    }

    @ApiOperation(value = "前台页面跳转", notes = "用于没有业务逻辑单纯跳转的页面")
    @RequestMapping(path = "${shieldsb.frontPath}/to/**", method = RequestMethod.GET)
    public String frontSkip2Page() {
        setAttributes();
        String uri = request.getServletPath();
        uri = uri.replace(frontPath + "/to/", "/");
        log.warn(uri);
        return uri;
    }

    @ApiOperation(value = "图片上传回调", notes = "")
    @RequestMapping(path = "uploadCallback", method = RequestMethod.GET)
    // 返回json格式
    @ResponseBody
    public Object uploadCallback() throws Exception {
        String result = getString("result");
        result = StringEscapeUtils.unescapeHtml(result); // 反转义，字符串可能被转义过
        JSONObject json_result = JSONObject.parseObject(result);
        if (result.indexOf("type") < 0) { // 兼容原有上传方法,原有方法不返回type
            return json_result;
        } else { // 只单图上传走这个
            String type = json_result.get("type").toString();
            if (type.indexOf(".") == 0) { // ueditor返回
                String imageHost = PropertiesModel.CONFIG.getString("uploadImageHost", "");
                json_result.put("url", imageHost + json_result.get("url").toString().replaceAll("http://(.*?)/", ""));
                // 附件保存至库
                if (StringUtils.isNotEmpty(json_result.getString("state")) && json_result.getString("state").equals("SUCCESS")) {
                    String name = json_result.getString("original");
                    String path = json_result.getString("url");
                    Long size = Long.parseLong(json_result.getString("size"));
                    AffixModel affixModel = new AffixModel();
                    affixModel.setName(name);
                    affixModel.setPath(path);
                    affixModel.setType(type);
                    affixModel.setSize(size);
                    affixModel.setAffixType(LdStaticParams.ATTFIX.ATTFIX_ONLINE);
                    sortService.saveAffixModel(affixModel);
                    json_result.put("affixId", affixModel.getId().toString()); // 转string防止太长丢失精度
                }
                return json_result;
            } else {
                return json_result;
            }
        }
    }

    @ApiOperation(value = "树形结构排序", notes = "")
    @RequestMapping(path = "resetTreeOrder", method = RequestMethod.POST)
    // 返回json格式
    @ResponseBody
    public Object resetTreeOrder(SortModel sortModel) throws ServletException, IOException {
        // asc=1显示，小的号码先显示
        return sortService.resetTreeOrder(sortModel);

    }

    @ApiOperation(value = "检测系统是否正常运行", notes = "")
    @GetMapping(path = "ping")
    @ResponseBody
    public Object ping() throws ServletException, IOException {
        return "1";
    }

    @ApiOperation(value = "获取系统版本号", notes = "")
    @GetMapping(path = "version")
    @ResponseBody
    public Object version() throws ServletException, IOException {
        return Version.VERSION;
    }

    @ApiOperation(value = "editormd的图片上传", notes = "")
    @RequestMapping("upload/editormdPic")
    @ResponseBody
    public Object editormdPic(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String dir = "/upload/editormd/pic/";

        String trueFileName = file.getOriginalFilename(); // 原文件名

        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        String fileName = System.currentTimeMillis() + "_" + StringUtils.getRandomNum(3) + suffix; // 生成文件名

        String path = request.getSession().getServletContext().getRealPath(dir);
        log.warn(path);

        File targetFile = new File(path, fileName);
        if (!targetFile.getParentFile().exists()) { // 上级目录不存在则级联创建
            targetFile.getParentFile().mkdirs();
        }

        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            log.error("", e);
        }

        JSONObject res = new JSONObject();
        res.put("url", LdGlobal.getProjectName() + dir + fileName);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }

    /**
     * 判断附件是否存在
     */
    @RequestMapping("isExitDownFile")
    @ResponseBody
    public Object isExitDownFile() throws ServletException, IOException {
        return basicService.isExitDownFile();
    }

    /**
     * 附件下载
     */
    @RequestMapping("downloadAtt")
    @ResponseBody
    public void downloadAtt() throws ServletException, IOException {
        basicService.downloadAtt();
    }

    @ApiOperation(value = "跳转初始化页面")
    @RequestMapping(path = "toSystemInit", method = RequestMethod.GET)
    public String toSystemInit() {
        if (SystemInitUtil.needInit()) {
            return "init";
        }
        return "redirect:" + adminPath; // 跳转搜索页面
    }

    @ApiOperation(value = "初始化")
    @RequestMapping(path = "systemInit", method = RequestMethod.POST)
    @ResponseBody
    public Object systemInit(SystemInitModel model) {
        setAttributes();
        Result result = systemInitService.systemInit(model);
        return result;
    }

}
